import sqlite3
from werkzeug.security import generate_password_hash, check_password_hash
from models import db, User

def get_db_connection():
    conn = sqlite3.connect('instance/group_info.db')
    conn.row_factory = sqlite3.Row
    return conn

def create_user(username, password):
    # 使用SQLAlchemy创建用户
    try:
        hashed_password = generate_password_hash(password)
        new_user = User(username=username, password=hashed_password, avatar='default_avatar.png')
        db.session.add(new_user)
        db.session.commit()
        return True
    except Exception as e:
        db.session.rollback()
        return False

def check_user(username, password):
    # 使用SQLAlchemy检查用户
    user = User.query.filter_by(username=username).first()
    if user and check_password_hash(user.password, password):
        return True
    return False

def get_user_by_username(username):
    return User.query.filter_by(username=username).first()
